package com.qk.filter;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取地址判断是否为登录，如果是登录，则放行
        String requestURI = request.getRequestURI();
        if(requestURI.equals("/login")){
            log.info("登录请求:{},放行",requestURI);
            filterChain.doFilter(request,response);
            return;
        }
        // 获取请求头中的token
        String token=request.getHeader("token");
        //检验 token是否为空，如果是空，则返回401，如果不是空，则解析token
        if(token==null|| token.isEmpty()){
            log.info("token不存在，返回401错误");
            response.setStatus(401);
            return;
        }
        //解析 token，如果解析失败，返回401错误
        try{
            Claims claims = JwtUtils.parseToken(token);

            Integer userId = claims.get("id",Integer.class);//获取用户ID
            log.info("当前用户ID存入ThreadLocal");
            CurrentUserHoler.setCurrentUser(userId);
        }catch (Exception  e){
            log.info("token解析失败，返回401错误");
            response.setStatus(401);
            return;
        }
        //放行
        log.info("token验证成功，放行");
        filterChain.doFilter(request,response);
        //释放资源
        log.info("释放资源");
        CurrentUserHoler.removeCurrentUser();
    }
}
